package cn.onlineclass.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class MybatisUtil {
    private static SqlSessionFactory sessionFactory ;
    private MybatisUtil(){

    }
    // 创建sessionFactory对象，因为整个应用程序只需要一个实例对象，故用静态代码块
    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回sessionFactory对象 工厂对象
     *
     * @return sessionFactory
     */
    public static SqlSessionFactory getSessionFactory() {
        return sessionFactory;
    }


    public static SqlSession get() {
        SqlSession session = sessionFactory.openSession();
        return session;
    }

    public static SqlSession get(boolean autoCommit) {
        SqlSession session = sessionFactory.openSession(autoCommit);
        return session;
    }
    /**
     * 关闭session对象，并从线程变量中删除
     */
    public static void closeSession(SqlSession session){
        if (session != null){
            session.commit();
            session.close();
        }
    }
}
